package com.java.interceptor;

import com.java.bean.User;
import com.java.contant.SSMContant;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthenInterceptor implements HandlerInterceptor {
   //1.拦截器前处理  请求到达前端控制器之前
    @Override
    public boolean preHandle(
                            HttpServletRequest request,
                            HttpServletResponse response,
                            Object o) throws Exception {
        //权限的校验
        //1.获取session对象
        HttpSession session = request.getSession();
        //2.获取用户信息
        User user = (User) session.getAttribute(SSMContant.USER);
        //3.判断是否登录
        if(user!=null){
            //登录  ->直接登录
            return true;
        }else {
            //未登录 重定向
            response.sendRedirect(request.getContextPath()+"/user/login");
            return false;
        }
    }
    //2.渲染视图之前
    @Override
    public void postHandle(
                            HttpServletRequest request,
                            HttpServletResponse response,
                            Object o,
                            ModelAndView modelAndView) throws Exception {
        //给modelAndView添加或修改数据
        System.out.println("渲染视图之前...");
    }
    //3.响应数据之前处理
    @Override
    public void afterCompletion(
                                HttpServletRequest request,
                                HttpServletResponse response,
                                Object o,
                                Exception e) throws Exception {

        System.out.println("响应数据之前...");
    }
}
